import { getHotSearchKey, getSearchMessge, getSearch } from '../../service/search'
import { debounce } from '../../utils/debounce'
import { strToNode } from '../../utils/strToNode'
const debounceSearch = debounce(getSearchMessge, 1000)
Page({

  /**
   * 页面的初始数据
   */
  data: {
    keyWords: [],
    suggestSongs: [],
    searchVal: '',
    resultSongs: [],
    nodes: [],
    hasMore: true
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.fetchData()
  },

  // 请求函数
  async fetchData() {
    const res = await getHotSearchKey()
    this.setData({ keyWords: res.result.hots })
  },
  async fetchDataByMessge(val) {

    const { result } = await debounceSearch(val)
    this.setData({ suggestSongs: result.allMatch })
    const { searchVal, suggestSongs } = this.data

    const keyWordList = suggestSongs?.map(i => i.keyword)
    const suggestSongsNodes = strToNode(keyWordList, searchVal)

    this.setData({ nodes: suggestSongsNodes })
  },
  async fetchSearch(searchVal) {
    wx.showLoading();
    try {
      const { hasMore, resultSongs } = this.data
      if (hasMore) {
        const res = await getSearch(searchVal)
        this.setData({ resultSongs: [...resultSongs, ...res.result.songs], hasMore: res.result.hasMore })
      } else {
        wx.showToast({
          title: "数据已经加载完毕",
        });
      }
    } finally {
      wx.hideLoading();
    }
  },

  // 事件处理 
  searchChange(e) {
    const keyWord = e.detail.trim();
    this.setData({ searchVal: keyWord })
    if (!keyWord) {
      this.setData({ suggestSongs: [] })
      this.setData({ resultSongs: [] })
      return
    }
    this.fetchDataByMessge(keyWord)
  },
  handleSarchAction(e) {
    const val = e.detail
    this.fetchSearch(val)
  },
  handleSongClick(e) {
    const { index, ishot } = e.currentTarget.dataset;
    let { keyWords, suggestSongs } = this.data
    let searchVal = ''
    if (ishot) {
      searchVal = keyWords[index].first
    } else {
      searchVal = suggestSongs[index].keyword
    }
    this.setData({ searchVal })
    this.fetchSearch(searchVal)
  },
  onPullDownRefresh() {
    console.log('触底');
    this.fetchSearch(this.data.searchVal);
  },

})